<template>
  <div class="wrapper">
    <!-- 搜索 -->
    <div class="search">
      <div class="search__back iconfont" @click="handleBackClick">&#xe679;</div>
      <div class="search__content">
        <div class="search__content__icon iconfont">&#xe699;</div>
        <input
          class="search__content__input"
          placeholder="请输入商品名称"
          v-model="keyword"
          @change="handleSearchInputChange"
        />
      </div>
    </div>
    <!--  -->
    <router-link
      v-for="item in searchList"
      :key="item._id"
      :to="`/shop/${item._id}`"
    >
      <ShopInfo :item="item" />
    </router-link>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { get } from '../../utils/request';
import ShopInfo from '../../components/ShopInfo.vue';

// 点击回退逻辑
const useBackRouterEffect = () => {
  const router = useRouter();
  const handleBackClick = () => {
    router.back();
  };
  return { handleBackClick };
};
// 获取搜索列表
const useSearchListEffect = () => {
  const searchList = ref([]);
  const getSearchList = async (keyword) => {
    let result = await get('/api/shop/search', { keyword });
    // console.log(result);
    if (result?.errno === 0 && result?.data?.length) {
      // console.log(result.data);
      searchList.value = result.data;
    }
  };
  return { searchList, getSearchList };
};

export default {
  name: 'SearchList',
  components: { ShopInfo },

  setup() {
    const route = useRoute();
    // 获取 keyword
    const keyword = ref(route.query.keyword || '');
    const handleSearchInputChange = () => {
      getSearchList(keyword.value);
    };

    const { handleBackClick } = useBackRouterEffect();
    // 获取搜索列表
    const { searchList, getSearchList } = useSearchListEffect();
    getSearchList();

    return { keyword, searchList, handleBackClick, handleSearchInputChange };
  },
};
</script>

<style lang="scss" scoped>
@import '../../style/variables.scss';
.wrapper {
  padding: 0 0.18rem;
}
.search {
  display: flex;
  margin: 0.14rem 0 0.04rem;
  line-height: 0.32rem;
  &__back {
    width: 0.3rem;
    font-size: 0.24rem;
    color: #b6b6b6;
  }
  &__content {
    display: flex;
    flex: 1;
    background: #f5f5f5;
    border-radius: 0.16rem;
    &__icon {
      width: 0.44rem;
      text-align: center;
      color: $search-fontColor;
    }
    &__input {
      width: 100%;
      padding: 0 0.2rem;
      border: none;
      outline: none;
      font-size: 0.16rem;
      color: $content-fontColor;
      font-size: 0.14rem;
      background: #f5f5f5;
      border-radius: 0.16rem;

      &::placeholder {
        color: $content-fontColor;
      }
    }
  }
}
</style>
